/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.onsite.assets;

import cn.ac.nercis.pes.common.constant.common.BaseConstants;
import cn.ac.nercis.pes.common.constant.evaluation.EvaluationConclusion;
import cn.ac.nercis.pes.common.constant.evaluation.EvaluationItem;
import cn.ac.nercis.pes.common.constant.knowledge.LayerTarget;
import cn.ac.nercis.pes.common.constant.manage.EvaluationEntryMode;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.common.utils.ConvertUtils;
import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.photo.ThumbnailControl;
import cn.ac.nercis.pes.community.constant.AppConstants;
import cn.ac.nercis.pes.community.controller.evaluation.onsite.BaseEvaluationController;
import cn.ac.nercis.pes.community.controller.evaluation.onsite.ChooseExpectedResultController;
import cn.ac.nercis.pes.community.controller.evaluation.onsite.EvalController;
import cn.ac.nercis.pes.community.controller.evaluation.photo.PhotoSelectController;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.support.controls.JFXPopup;
import cn.ac.nercis.pes.community.utils.ControlUtils;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.onsite.ChooseExpectedResultView;
import cn.ac.nercis.pes.community.views.evaluation.onsite.EvalView;
import cn.ac.nercis.pes.community.views.evaluation.photo.PhotoSelectView;
import cn.ac.nercis.pes.model.dto.evaluation.onsite.EvaluationRecordDTO;
import cn.ac.nercis.pes.model.dto.knowledge.KmExpectedResultDTO;
import cn.ac.nercis.pes.model.dto.knowledge.KmSimpleTargetDTO;
import cn.ac.nercis.pes.service.evaluation.EvaluationRecordService;
import cn.ac.nercis.pes.service.knowledge.KmEvaluationRecordService;
import cn.ac.nercis.pes.service.knowledge.KmExpectedResultService;
import cn.ac.nercis.pes.service.utils.CalculateUtils;
import cn.ac.nercis.pes.service.utils.FileManage;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * 系统资产测评管理控制器（管理类型）
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class AssetManageEvalController extends BaseEvaluationController {

    @FXML
    private VBox workspaceBox;
    @FXML
    private HBox evalTargetBox;
    @FXML
    private Label assetNameLbl;
    @FXML
    private Label currentTargetLbl;

    @FXML
    private StackPane unitTargetPane;
    @FXML
    private HBox judgeOptionBox;
    @FXML
    private ComboBox<String> resultCombo;
    @FXML
    private Label notApplyResult;

    @FXML
    private ListView<MenuVO> menuListView;
    @FXML
    private Button tmpSaveButton;
    @FXML
    private Button saveButton;
    @FXML
    private VBox targetDescBox;
    @FXML
    private Label evaMethodLbl;
    @FXML
    private HBox evaDescBlock;
    @FXML
    private VBox evaDescBox;
    @FXML
    private Label scoreLbl;
    @FXML
    private VBox resultBlock;
    @FXML
    private VBox notApplyBlock;
    @FXML
    private FlowPane pictureBox;
    @FXML
    private TextArea contentTxt;

    @FXML
    private TextArea notApplyContentTxt;

    @FXML
    private StackPane evalDescPane;

    private final StringProperty layerTargetName = new SimpleStringProperty();
    private final ObjectProperty<EvaluationEntryMode> entryMode = new SimpleObjectProperty<>();
    private final BooleanBinding dakMode;
    private final EvaluationRecordService evaluationRecordService;
    private final KmExpectedResultService expectedResultService;
    private final ExecutorService executorService;
    private final KmEvaluationRecordService kmEvaluationRecordService;

    private String currentSystemId;
    private MenuVO currentAsset;
    private KmSimpleTargetDTO currentLayerTarget;
    private MenuVO currentUnitTarget;
    private EvaluationRecordDTO currentEvaluationRecord;
    private StackPane page;
    private PageDialog pageDialog;
    private JFXPopup unitTargetPopup;

    public AssetManageEvalController() {
        this.evaluationRecordService = SpringUtils.getBean(EvaluationRecordService.class);
        this.expectedResultService = SpringUtils.getBean(KmExpectedResultService.class);
        this.executorService = SpringUtils.getBean(ExecutorService.class);
        this.kmEvaluationRecordService = SpringUtils.getBean(KmEvaluationRecordService.class);
        this.dakMode = Bindings.createBooleanBinding(this::isDakMode, entryMode);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        currentTargetLbl.setGraphic(IconUtils.getGlyph("expand-menu-icon","expand-menu-icon"));
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        tmpSaveButton.disableProperty().bind(dataSaving);
        saveButton.disableProperty().bind(dataSaving);

        EvaluationConclusion.findAllByManage().forEach(item->resultCombo.getItems().add(item.getName()));
        bindVisibleAndManage(judgeOptionBox,notApplyResult,evaDescBlock,resultBlock,notApplyBlock);
        initMenus();
//        initTextEditor(contentTxt,notApplyContentTxt);
        //附加复制功能
        ControlUtils.appendCopy(assetNameLbl,this::onCopySuccessTip);
        ControlUtils.appendCopy(evaMethodLbl,this::onCopySuccessTip);
        ControlUtils.appendCopy(evaDescBox,this::onCopySuccessTip);

        GuiStore.applyQuickSave(this.workspaceBox,this::onGlobalSave);
    }

    public void initializeData(String systemId,MenuVO currentAsset, KmSimpleTargetDTO layerTarget) {
        this.currentSystemId = systemId;
        this.currentAsset = currentAsset;
        this.currentLayerTarget = layerTarget;
        this.realTimeSaveManager.setEnable(false);
        LogUtils.info(log, "初始化管理类指标测评对象内容...");
        layerTargetName.setValue(layerTarget.getName());
        var evalView = AppStore.getEvaluationView(this.currentSystemId, EvalView.class);
        if(evalView.getController() instanceof EvalController controller){
            this.page = controller.getPage();
        }
        ControlUtils.setLabelTextByLimit(assetNameLbl, currentAsset.getToolTip(), AppConstants.MAX_SHOW_TEXT_LENGTH);
        this.loadMenuData();
    }

    public StringProperty layerTargetNameProperty(){
        return layerTargetName;
    }
    public String getLayerTargetName(){
        return layerTargetName.getValue();
    }

    @FXML
    public void onTmpSave() {
        LogUtils.info(log, "执行暂存操作...");
        saveEvaluationRecord(false);
    }

    @FXML
    public void onFinishSave(){
        LogUtils.info(log, "执行保存操作...");
        saveEvaluationRecord(true);
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        saveEvaluationRecord(false,false);
    }

    @Override
    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        this.saveEvaluationRecord(true,false);
    }

    @FXML
    public void onAddFileClick(){
        LogUtils.info(log, "执行添加证据文件操作...");
        var selectView = AppStore.getEvaluationView(this.currentSystemId, PhotoSelectView.class);
        pageDialog = PageDialog.builder()
                .withIcon("dialog-edit-icon")
                .withTitle("选择证据文件")
                .withContent(Objects.requireNonNull(selectView).load())
                .withOwner(AppStore.getCurrentSystem(this.currentSystemId).getEvaluationStage())
                .build();
        pageDialog.setYesText("确定");
        pageDialog.setNoText("取消");
        if(selectView.getController() instanceof PhotoSelectController controller){
            controller.initializeData(this.currentSystemId, LayerTarget.fromName(currentLayerTarget.getName()));
        }
        pageDialog.show(this::savePhotoFile);
    }

    @FXML
    public void onUnitTargetPopup(){
        unitTargetPopup.show(evalTargetBox, JFXPopup.PopupVPosition.TOP,JFXPopup.PopupHPosition.LEFT,
                0,currentTargetLbl.getHeight()+10);
    }

    @FXML
    public void onShowDescClick(){
        LogUtils.info(log, "查看测评说明操作...");
        this.showAssetEvalMethod(this.currentSystemId,this.currentAsset.getCode(),this.currentLayerTarget, this.currentUnitTarget.getCode(),
                ()->loadEvaluationRecord(this.currentUnitTarget));
    }


    @FXML
    public void onResultClick() {
        LogUtils.info(log, "执行结论点击操作...");
        EvaluationConclusion evalConclusion = Optional.ofNullable(resultCombo.getSelectionModel().getSelectedItem())
                .map(EvaluationConclusion::fromName)
                .orElse(EvaluationConclusion.DEFAULT);
        if (evalConclusion == EvaluationConclusion.DEFAULT) {
            return;
        }
        LogUtils.info(log, "获取预期结果信息...");
        LogUtils.record(log, "请求数据，layerTarget：{},unitTarget:{},assetId:{}", currentLayerTarget.getName(),
                currentUnitTarget.getTitle(), currentAsset.getCode());
        CompletableFuture.supplyAsync(() -> expectedResultService.findExpectedResults(currentLayerTarget.getName(),
                        currentUnitTarget.getTitle(), currentAsset.getCode(), EvaluationItem.MANAGE, evalConclusion),executorService)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        if (CollectionUtils.isNotEmpty(res.getData())) {
                            selectedExpectedResult(res.getData());
                        }
                    } else {
                        AppUtils.showMessageDialog(res.getMsg(), MessageType.WARN,this.page);
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("获取预期结果信息出错!", ex);
                    return null;
                });
    }

    @FXML
    public void onResultChange() {
        if(!realTimeSaveManager.getEnable()){
            return;
        }
        LogUtils.info(log, "执行结论变更操作...");
        EvaluationConclusion result = Optional.ofNullable(resultCombo.getSelectionModel().getSelectedItem())
                .map(EvaluationConclusion::fromName)
                .orElse(EvaluationConclusion.DEFAULT);
        currentEvaluationRecord.setConclusion(result);
        CalculateUtils.calculateManageScore(currentEvaluationRecord);
        scoreLbl.setText(ConvertUtils.scoreToString(currentEvaluationRecord.getScore()));
        realTimeSaveManager.onChange();
    }


    public ObjectProperty<EvaluationEntryMode> entryModeProperty() {
        return entryMode;
    }
    public EvaluationEntryMode getEntryMode() {
        return entryMode.get();
    }
    public BooleanBinding dakModeProperty() {
        return dakMode;
    }
    public boolean isDakMode() {
        return getEntryMode() == EvaluationEntryMode.DAK_MODE;
    }

    private void saveEvaluationRecord(boolean finishSave){
        this.saveEvaluationRecord(false,finishSave);
    }
    private void saveEvaluationRecord(boolean realTime,boolean finishSave) {
        collectEvaluationRecordData();
        if (validContent()) {
            checkEvaluationConclusion(realTime,finishSave);
        }
    }
    private void collectEvaluationRecordData(){
        if(!currentEvaluationRecord.getIsApply()){
            currentEvaluationRecord.setContent(notApplyContentTxt.getText());
            return;
        }
        var result = Optional.ofNullable(resultCombo.getSelectionModel().getSelectedItem())
                .map(EvaluationConclusion::fromName)
                .orElse(EvaluationConclusion.DEFAULT);
        currentEvaluationRecord.setConclusion(result);
        currentEvaluationRecord.setContent(contentTxt.getText());
    }

    protected void checkEvaluationConclusion(boolean realTime,boolean finishSave) {
        if (StringUtils.isEmpty(currentEvaluationRecord.getId())) {
            saveData(realTime,finishSave);
            return;
        }
        dataSaving.setValue(true);
        LogUtils.info(log, "测评结果变更前检查...");
        LogUtils.record(log, "请求数据:{}", currentEvaluationRecord);
        CompletableFuture.supplyAsync(() -> evaluationRecordService.checkEvaluationConclusion(currentEvaluationRecord),executorService)
                .thenAccept(res -> Platform.runLater(() -> {
                    dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        saveData(realTime,finishSave);
                    } else {
                        AlertDialog alertDialog = AlertDialog.builder()
                                .withMode(AlertMode.CONFIRM)
                                .withType(AlertType.WARN)
                                .withTitle("操作提示")
                                .withContent(res.getMsg())
                                .withContainer(this.page)
                                .build();
                        alertDialog.show((confirm) -> {
                            if (confirm) {
                                saveData(realTime,finishSave);
                            } else {
                                loadEvaluationRecord(currentUnitTarget);
                            }
                        });
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("测评结果变更前检查出错!", ex);
                    return null;
                });
    }

    private void saveData(boolean realTime,boolean finishSave) {
        dataSaving.setValue(true);
        LogUtils.info(log, "保存测评记录信息...");
        LogUtils.record(log, "请求数据:{}", currentEvaluationRecord);
        CompletableFuture.supplyAsync(() -> evaluationRecordService.saveAssetEvaluationRecord(currentEvaluationRecord),executorService)
                .thenAccept(res -> Platform.runLater(() -> {
                    dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                        //重新加载内容数据
                        initEvaluationRecord(res.getData());
                        this.setRecordFinishState(finishSave);
                        ControlUtils.refreshScoreInfo(this.currentSystemId);
                        this.checkUnitNotApply();
                    } else {
                        if(realTime){
                            log.error("即时保存测评记录信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("保存测评记录信息出错!", ex);
                    return null;
                });
    }

    private void checkUnitNotApply(){
        LogUtils.info(log, "检查当前管理类型单元指标下的现场记录是否全为不适用...");
        CompletableFuture.supplyAsync(() -> evaluationRecordService.checkUnitTargetNotApply(currentSystemId,currentEvaluationRecord.getUnitTargetId()),executorService)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (!res.isSuccess()) {
                        AlertDialog.builder()
                                .withContainer(this.page)
                                .withTitle("系统提示")
                                .withContent(res.getMsg())
                                .withMode(AlertMode.ALERT)
                                .withType(AlertType.WARN)
                                .build()
                                .show();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("检查当前管理类型单元指标下的现场记录是否全为不适用出错!", ex);
                    return null;
                });
    }

    private void setRecordFinishState(boolean finishSave){
        FinishState state = finishSave ? FinishState.FINISH : FinishState.INCOMPLETE;
        CompletableFuture.supplyAsync(()->evaluationRecordService.setRecordFinishState(currentEvaluationRecord.getId(),state),executorService)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshFinishState(state);
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL).withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("设置测评进度信息出错!", ex);
                    return null;
                });
    }

    private void refreshFinishState(FinishState state){
        currentUnitTarget.setIcon(ControlUtils.finishStateToIcon(state));
        currentUnitTarget.setState(state);
        menuListView.refresh();
        var evalView = AppStore.getEvaluationView(this.currentSystemId,EvalView.class);
        if(evalView.getController() instanceof EvalController controller){
            controller.refreshAssetNode(currentAsset.getCode());
        }
    }

    private boolean validContent() {
        if (StringUtils.length(currentEvaluationRecord.getContent()) > AppConstants.MAX_RECORD_CONTENT_LENGTH) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN).withMessage("内容描述不能超出2000个字！")
                    .build().show();
            return false;
        }
        return true;
    }

    private void savePhotoFile(){
        List<File> addFiles = getSelectedPhotoFiles();
        List<File> photoFiles = this.pictureBox.getChildren()
                .stream()
                .filter(n->n instanceof ThumbnailControl)
                .map(n->(ThumbnailControl)n)
                .map(ThumbnailControl::getPictureFile)
                .toList();
        addFiles.stream()
                .filter(file->photoFiles.stream().noneMatch(pf->StringUtils.equals(file.getPath(),pf.getPath())))
                .forEach(this::addPhotoImage);
        this.collectManageFiles();
        this.pageDialog.close();
    }
    private List<File> getSelectedPhotoFiles(){
        var selectView = AppStore.getEvaluationView(this.currentSystemId,PhotoSelectView.class);
        List<File> addFiles = new ArrayList<>();
        if(selectView.getController() instanceof PhotoSelectController controller){
            addFiles.addAll(controller.selectedPhotoFile());
        }
        return addFiles;
    }

    private void selectedExpectedResult(List<KmExpectedResultDTO> expectedResults) {
        var resultView = AppStore.getEvaluationView(this.currentSystemId, ChooseExpectedResultView.class);
        pageDialog = PageDialog.builder()
                .withIcon("dialog-edit-icon")
                .withTitle("选择预期结果信息")
                .withContent(Objects.requireNonNull(resultView).load())
                .withOwner(AppStore.getCurrentSystem(this.currentSystemId).getEvaluationStage())
                .build();
        pageDialog.setYesText("确定");
        pageDialog.setNoText("取消");
        if(resultView.getController() instanceof ChooseExpectedResultController controller){
            controller.initializeData(this.currentSystemId,this.currentAsset.getToolTip(),expectedResults);
        }
        pageDialog.show(this::applyExpectedResult);
    }

    private void applyExpectedResult() {
        String result = SpringUtils.getBean(ChooseExpectedResultController.class).selectedExpectedResult();
        if (StringUtils.isBlank(result)) {
            AppUtils.showMessageDialog("请选择使用的预期结果！",MessageType.WARN,this.page);
            return;
        }
        contentTxt.setText(result);
        pageDialog.close();
    }

    private void loadMenuData() {
        menuListView.getItems().clear();
        LogUtils.info(log, "获取系统资产关联单元指标信息...");
        LogUtils.record(log, "请求数据，systemId：{},data:{}", this.currentSystemId,
                currentAsset.getCode(), currentLayerTarget.getId());
        CompletableFuture.supplyAsync(() -> evaluationRecordService.findUnitTargetByAsset(this.currentSystemId,
                        currentAsset.getCode(), currentLayerTarget.getId()),executorService)
                .thenAccept(res -> Platform.runLater(() -> {
                    res.forEach(ute -> {
                        var item = new MenuVO(2,ute.getUnitTargetId(),ute.getUnitTargetName(),
                                ControlUtils.finishStateToIcon(ute.getFinishState()));
                        item.setState(ute.getFinishState());
                        menuListView.getItems().add(item);
                    });
                    selectedDefaultMenu();
                }))
                .exceptionally((ex) -> {
                    log.error("获取系统资产关联单元指标信息出错!", ex);
                    return null;
                });
    }
    private void selectedDefaultMenu(){
        boolean isSelected = false;
        for(MenuVO menuObj : menuListView.getItems()){
            isSelected = selectedDefaultMenu(menuObj,menuListView);
            if(isSelected){
                break;
            }
        }
        if(!isSelected){
            menuListView.getSelectionModel().select(0);
        }
    }
    private boolean selectedDefaultMenu(MenuVO menuLabel,ListView<MenuVO> menu){
        if(Objects.isNull(menuLabel) || StringUtils.equals(menuLabel.getIcon(),"finish-process-icon")){
            return false;
        }
        menu.getSelectionModel().select(menuLabel);
        return true;
    }

    private void initMenus(){
        menuListView.setCellFactory(listView -> new MenuListCell(MAX_SHOW_MENU_TEXT_LENGTH,true));
        menuListView.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if(this.unitTargetPopup.isShowing()){
                        this.unitTargetPopup.hide();
                    }
                    if(Objects.nonNull(newValue)){
                        loadEvaluationRecord(newValue);
                    }
                });
        unitTargetPopup = new JFXPopup(unitTargetPane);
        unitTargetPopup.showingProperty().addListener((observableValue, oldValue, newValue) -> {
            if(newValue){
                currentTargetLbl.setGraphic(IconUtils.getGlyph("fold-menu-icon","expand-menu-icon"));
            }else{
                currentTargetLbl.setGraphic(IconUtils.getGlyph("expand-menu-icon","expand-menu-icon"));
            }
        });
    }

    private void loadEvaluationRecord(MenuVO unitTargetEval) {
        this.currentUnitTarget = unitTargetEval;
        this.currentTargetLbl.setText(unitTargetEval.getTitle());
        LogUtils.info(log, "获取【管理类型】测评记录信息...");
        LogUtils.record(log, "请求数据，systemId：{},assetId:{},unitTargetId:{}", this.currentSystemId,
                currentAsset.getCode(), unitTargetEval.getCode());
        CompletableFuture.supplyAsync(() -> evaluationRecordService.getAssetEvaluationRecord(this.currentSystemId,
                        currentAsset.getCode(), unitTargetEval.getCode()),executorService)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        initEvaluationRecord(res.getData());
                    } else {
                        AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("获取【管理类型】测评记录信息出错!", ex);
                    return null;
                });
    }

    private void initEvaluationRecord(EvaluationRecordDTO evaluationRecord){
        realTimeSaveManager.setEnable(false);
        this.currentEvaluationRecord= evaluationRecord;
        this.assetNameLbl.setText(currentAsset.getToolTip());
        this.setContent(targetDescBox,currentEvaluationRecord.getTargetDesc());
        this.setEvalMethod(evaMethodLbl,currentEvaluationRecord.getMethod());
        if(StringUtils.isBlank(currentEvaluationRecord.getDesc())){
            this.evaDescBox.getChildren().clear();
            this.evaDescBox.setVisible(false);
        }else{
            this.setContent(evaDescBox,currentEvaluationRecord.getDesc());
        }
        if(evaluationRecord.getIsApply()){
            resultBlock.setVisible(true);
            this.changeResultTab(judgeOptionBox,notApplyResult,notApplyBlock);
            scoreLbl.setText(ConvertUtils.scoreToString(currentEvaluationRecord.getScore()));
            this.initEvalResult();
        }else{
            notApplyBlock.setVisible(true);
            this.changeResultTab(notApplyResult, judgeOptionBox, resultBlock);
            notApplyContentTxt.setText(evaluationRecord.getContent());
            scoreLbl.setText(BaseConstants.EMPTY_SCORE_TAG);
        }
        realTimeSaveManager.setEnable(true);
    }

    private void initEvalResult(){
        resultCombo.getSelectionModel().select(currentEvaluationRecord.getConclusion().getName());
        contentTxt.setText(currentEvaluationRecord.getContent());
        this.initEvalResultFiles();
    }

    private void initEvalResultFiles(){
        pictureBox.getChildren().clear();
        if(StringUtils.isBlank(currentEvaluationRecord.getManageFiles())){
            return;
        }
        String[] photoFileNames = StringUtils.split(currentEvaluationRecord.getManageFiles(),BaseConstants.MULTI_SPLIT_CHAR);
        List<File> photoFiles = FileManage.findPhotoFiles(this.currentSystemId);
        for(String fileName:photoFileNames){
            photoFiles.stream()
                    .filter(f->StringUtils.equals(f.getName(),fileName))
                    .findFirst().ifPresent(this::addPhotoImage);
        }
    }

    private void addPhotoImage(File pictureFile){
        if(!pictureFile.exists()){
            return;
        }
        try {
            ThumbnailControl thumbnailControl = new ThumbnailControl(pictureFile,this.page);
            thumbnailControl.setEnableModify(false);
            thumbnailControl.setEnableSelected(false);
            thumbnailControl.setOnDeleteEvent(this::onDeleteFileClick);
            pictureBox.getChildren().add(thumbnailControl);
        }catch (IOException ex){
            log.error("加载证据文件失败：",ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage("载入证据文件失败")
                    .build().show();
        }
    }

    protected void onDeleteFileClick(ThumbnailControl source){
        LogUtils.info(log, "执行删除当前证据文件操作...");
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("是否删除当前证据文件？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            this.pictureBox.getChildren().remove(source);
            this.collectManageFiles();
        });
    }

    private void collectManageFiles(){
        String fileNames = this.pictureBox.getChildren()
                .stream()
                .filter(n->n instanceof ThumbnailControl)
                .map(n->(ThumbnailControl)n)
                .map(ThumbnailControl::getPictureFile)
                .map(File::getName)
                .collect(Collectors.joining(BaseConstants.MULTI_SPLIT_CHAR));
        this.currentEvaluationRecord.setManageFiles(fileNames);
        realTimeSaveManager.onChange();
    }


    private void onCopySuccessTip(){
        if(Objects.nonNull(this.page)){
            AppUtils.showMessageDialog("复制成功！", MessageType.SUCCESS,this.page);
        }
    }

}